package com.pimee.support.shiro.credentials;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;

import com.pimee.common.util.Md5Util;
import com.pimee.model.SysUser;

import lombok.extern.slf4j.Slf4j;

/**
 * Shiro-匹配器
 * 
 * @description
 * @author Bruce Shaw 2020年3月5日 下午4:56:14
 */
@Slf4j
public class CredentialsMatcher extends SimpleCredentialsMatcher {
	// 重写父类的方法,用于验证密码有效性
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		UsernamePasswordToken intoken = (UsernamePasswordToken) token;
		SysUser sysUser = (SysUser) info.getPrincipals().getPrimaryPrincipal();
		// 获取用户输入的密码
		String originPasswd = new String(intoken.getPassword());
		// 获得数据库的密码
		String dbPassword = (String) sysUser.getPassword();
		try {
			originPasswd = Md5Util.getMd5Passwd(originPasswd, sysUser.getSalt());
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		log.info("===> 校验密码 originPasswd:{}, dbPassword:{}", originPasswd, dbPassword);
		// 验证密码是否一致
		return this.equals(dbPassword, originPasswd);
	}

	public static void main(String[] args) {
		String pwd = Md5Util.getMd5Passwd("123456", "2e70cc");
		System.out.println(pwd);
	}
}
